package com.dsideal.cloud.cas.client.utils;

import com.dsideal.cloud.auth.common.constant.AuthConstants;
import com.dsideal.cloud.auth.common.util.StringHelper;
import com.dsideal.cloud.auth.common.util.jwt.IJWTInfo;
import com.dsideal.cloud.auth.common.util.jwt.JWTInfo;
import com.dsideal.cloud.auth.common.util.jwt.RsaKeyHelper;
import com.dsideal.cloud.common.entity.Roles;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author suny
 */
public class JWTHelperForCas {
    private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();

    /**
     * 密钥加密token
     *
     * @param jwtInfo
     * @param priKeyPath
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(IJWTInfo jwtInfo, String priKeyPath, int expire) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(jwtInfo.getUniqueName())
                .claim(AuthConstants.JWT_KEY_USER_ID, jwtInfo.getId())
                .claim(AuthConstants.JWT_KEY_NAME, jwtInfo.getName())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKeyPath))
                .compact();
        return compactJws;
    }

    /**
     * 密钥加密token
     *
     * @param jwtInfo
     * @param priKey
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(IJWTInfo jwtInfo, byte priKey[], int expire) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(jwtInfo.getUniqueName())
                .claim(AuthConstants.JWT_KEY_USER_ID, jwtInfo.getId())
                .claim(AuthConstants.JWT_BUREAU_id,jwtInfo.getBureauId())
                .claim(AuthConstants.JWT_KEY_NAME, jwtInfo.getName())
                .claim(AuthConstants.JWT_KEY_AUTHORITIES, jwtInfo.getAuthorities())
                .claim(AuthConstants.JWT_KEY_ROLES, jwtInfo.getRoles())
                // 设置过期时间
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKey))
                .compact();
        return compactJws;
    }

    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
        return claimsJws;
    }

    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey(rsaKeyHelper.getPublicKey(pubKey))
                .parseClaimsJws(token);
        return claimsJws;
    }

    /**
     * 获取token中的用户信息
     *
     * @param token
     * @param pubKeyPath
     * @return
     * @throws Exception
     */
    public static IJWTInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
        Claims body = claimsJws.getBody();
        return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(AuthConstants.JWT_BUREAU_id)),
                StringHelper.getObjectValue(body.get(AuthConstants.JWT_KEY_USER_ID)),
                new ArrayList<>((List<Roles>)body.get(AuthConstants.JWT_KEY_ROLES)),
                StringHelper.getObjectValue(body.get(AuthConstants.JWT_KEY_NAME)));
    }

    /**
     * 获取token中的服务信息
     *
     * @param token
     * @param pubKey
     * @return
     * @throws Exception
     */
    public static IJWTInfo getInfoFromToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKey);
        Claims body = claimsJws.getBody();
        return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(AuthConstants.JWT_BUREAU_id)),
                StringHelper.getObjectValue(body.get(AuthConstants.JWT_KEY_USER_ID)),
                new ArrayList<>((List<Roles>)body.get(AuthConstants.JWT_KEY_ROLES)),
                StringHelper.getObjectValue(body.get(AuthConstants.JWT_KEY_NAME)));
    }

    /**
     * 获取token中的用户信息
     *
     * @param token
     * @param pubKey
     * @return
     * @throws Exception
     */
    public static IJWTInfo getUserInfoFromToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKey);
        Claims body = claimsJws.getBody();
        return new JWTInfo(body.getSubject(),
                StringHelper.getObjectValue(body.get(AuthConstants.JWT_KEY_USER_ID)),
                StringHelper.getObjectValue(body.get(AuthConstants.JWT_KEY_NAME)),
                new HashSet<>((ArrayList<String>) body.get(AuthConstants.JWT_KEY_AUTHORITIES)),
                new ArrayList<>((List<Roles>) body.get(AuthConstants.JWT_KEY_ROLES)));
    }
}
